package ui.panels;

import entities.EmployeeDepartmentHistory;
import entities.Shift;
import entities.User;
import java.awt.Color;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import manager.GenericDriver;
import manager.ManagerDriver;
import model.ViewShiftComboBoxModel;
import ui.windows.RemedySchedulerFrame;
import ui.windows.UserChooserDialog;

/**
 *
 * @author viev
 */
public class CreateHeadSchedulerPanel extends javax.swing.JPanel {

    /** Creates new form CreateHeadSchedulerPanel */
    public CreateHeadSchedulerPanel(RemedySchedulerFrame mainFrame, HeadSchedulerManagementPanel parentPanel) {
        this.mainFrame = mainFrame;
        this.parentPanel = parentPanel;
        driver = (ManagerDriver) mainFrame.getDriver();
        genDriver = mainFrame.getGenericDriver();
        initComponents();
        includeModel();

    }

    private void includeModel() {
        model = new ViewShiftComboBoxModel(genDriver.showShift());
        cbShifts.setModel(model);
        checkSelected();
        checkShift();
        checkDate();
        dialog = new UserChooserDialog(mainFrame);
        lbID.setText("?");
        lbDep.setText("?");
        lbCheckDate.setText("");
        lbMessage.setText(" ");
    }

    private void createRecord() {
        checkVal();
        if (checkVal) {
            Shift selectedShift = (Shift) cbShifts.getSelectedItem();
            EmployeeDepartmentHistory record = new EmployeeDepartmentHistory();
            record.setEmployeeID(selectedUser.getUserID());
            record.setDepartmentID(selectedUser.getDepartmentID());
            record.setShiftID(selectedShift.getShiftID());
            record.setStartDate(getOnlyDate(dcStartDate.getDate()));
            record.setEndDate(getOnlyDate(dcEndDate.getDate()));
            boolean returnVal = parentPanel.createEmployeeDepartmentH(record);
            if (returnVal) {
                close();
                JOptionPane.showMessageDialog(null, "New record is created");
            } else {
                JOptionPane.showMessageDialog(null, "Cannot insert", "Error", JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    public void setSeletedRecord(User user) {
        this.selectedUser = user;
        checkSelected();
        if (selected) {
            lbID.setText(selectedUser.getLoginID());
            lbDep.setText(selectedUser.getDepartmentName());
        }
    }

    private void checkSelected() {
        if (selectedUser != null) {
            selected = true;
        } else {
            selected = false;
        }
    }

    private void checkShift() {
        Shift shift = (Shift) cbShifts.getSelectedItem();
        if (shift != null) {
            lbCheckShift.setText("");
            checkShift = true;
        } else {
            lbCheckShift.setText("choise shift...");
            lbCheckShift.setForeground(Color.blue);
            checkShift = false;
        }
    }

    private void checkDate() {
        Date startDate = getOnlyDate(dcStartDate.getDate());
        Date endDate = getOnlyDate(dcEndDate.getDate());
        if (startDate != null) {
            if (endDate != null && endDate.before(startDate)) {
                lbCheckDate.setText("enter invalid !");
                lbCheckDate.setForeground(Color.red);
                checkDate = false;
            } else {
                lbCheckDate.setText("");
                checkDate = true;
            }
        } else {
            checkDate = false;
        }
    }

    private void checkVal() {
        checkSelected();
        checkShift();
        checkDate();
        checkTime();
        checkTime();
        if (selected && checkShift && checkDate && checkTime) {
            Shift selectedShift = (Shift) cbShifts.getSelectedItem();
            Date startDate = getOnlyDate(dcStartDate.getDate());
            int eid = selectedUser.getUserID();
            int did = selectedUser.getDepartmentID();
            int sid = selectedShift.getShiftID();
            boolean returnVal = parentPanel.containtPK(eid, did, sid, startDate);
            if (!returnVal) {
                lbMessage.setText("");
                checkVal = true;
            } else {
                lbMessage.setText("existed !");
                lbMessage.setForeground(Color.red);
                checkVal = false;
            }
        } else {
            checkVal = false;
        }
    }

    private void checkTime() {
        if (selectedUser != null && checkShift && checkDate) {
            EmployeeDepartmentHistory record = new EmployeeDepartmentHistory();
            record.setEmployeeID(selectedUser.getUserID());
            Shift selectedShift = (Shift) cbShifts.getSelectedItem();
            record.setShiftID(selectedShift.getShiftID());
            record.setStartDate(getOnlyDate(dcStartDate.getDate()));
            record.setEndDate(getOnlyDate(dcEndDate.getDate()));
            checkTime = parentPanel.timeValid(record);
            if (!checkTime) {
                lbMessage.setText("duplicate !");
                lbMessage.setForeground(Color.red);
            }
        }
    }
    
    private Date getOnlyDate(Date date) {
        if(date == null)
            return null;
        return new Date(date.getYear(), date.getMonth(), date.getDate());
    }

    private void clear() {
        selectedUser = null;
        lbID.setText("?");
        lbDep.setText("?");
        cbShifts.setSelectedItem(null);
        dcStartDate.setDate(null);
        dcEndDate.setDate(null);
        checkShift();
        checkDate();
    }

    private void showChoseUser() {
        dialog.setLocationRelativeTo(null);
        dialog.showUserChooser(UserChooserDialog.SELECT_HEAD_MODE);
        new Thread() {

            @Override
            public void run() {
                while (dialog.isVisible()) {
                    try {
                        sleep(10);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(CreateHeadSchedulerPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                setSeletedRecord(dialog.getUser());
            }
        }.start();
    }

    private void close() {
        clear();
        parentPanel.closeTarget();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private RemedySchedulerFrame mainFrame;
    private HeadSchedulerManagementPanel parentPanel;
    private ManagerDriver driver;
    private GenericDriver genDriver;
    private ViewShiftComboBoxModel model;
    private User selectedUser;
    private boolean selected;
    private boolean checkShift;
    private boolean checkDate;
    private boolean checkTime;
    private boolean checkVal;
    private UserChooserDialog dialog;
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbClose = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lbID = new javax.swing.JLabel();
        lbDep = new javax.swing.JLabel();
        cbShifts = new javax.swing.JComboBox();
        lbCheckShift = new javax.swing.JLabel();
        dcStartDate = new com.toedter.calendar.JDateChooser();
        dcEndDate = new com.toedter.calendar.JDateChooser();
        lbCheckDate = new javax.swing.JLabel();
        lbMessage = new javax.swing.JLabel();
        lbChoise = new javax.swing.JLabel();
        bCreate = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));

        lbClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/close_20.png"))); // NOI18N
        lbClose.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbCloseMouseClicked(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Head's Scheduler", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 14))); // NOI18N

        jLabel2.setText("ID:");

        jLabel3.setText("Department:");

        jLabel4.setText("Shift:");

        jLabel5.setText("Start Date:");

        jLabel6.setText("End Date:");

        lbID.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbID.setText("value");

        lbDep.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbDep.setText("value");

        cbShifts.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbShifts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbShiftsActionPerformed(evt);
            }
        });

        lbCheckShift.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbCheckShift.setText("value");

        lbCheckDate.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbCheckDate.setText("value");

        lbMessage.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lbMessage.setText("value");

        lbChoise.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbChoise.setForeground(new java.awt.Color(0, 0, 204));
        lbChoise.setText("choise...");
        lbChoise.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbChoiseMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                lbChoiseMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                lbChoiseMouseExited(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(89, 89, 89)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbDep)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(dcEndDate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dcStartDate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cbShifts, javax.swing.GroupLayout.Alignment.LEADING, 0, 126, Short.MAX_VALUE)
                            .addComponent(lbID, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lbChoise)
                            .addComponent(lbCheckShift, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                            .addComponent(lbCheckDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(75, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lbID)
                    .addComponent(lbChoise))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lbDep))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbShifts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbCheckShift))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(dcStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbCheckDate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(dcEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbMessage)
                .addContainerGap(63, Short.MAX_VALUE))
        );

        bCreate.setText("Create");
        bCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCreateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(bCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                .addComponent(lbClose)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbClose)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bCreate)
                .addContainerGap(122, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void lbCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbCloseMouseClicked
    close();
}//GEN-LAST:event_lbCloseMouseClicked

private void lbChoiseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbChoiseMouseClicked
    showChoseUser();
}//GEN-LAST:event_lbChoiseMouseClicked

private void lbChoiseMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbChoiseMouseEntered
    lbChoise.setForeground(Color.red);
}//GEN-LAST:event_lbChoiseMouseEntered

private void lbChoiseMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbChoiseMouseExited
    lbChoise.setForeground(Color.blue);
}//GEN-LAST:event_lbChoiseMouseExited

private void bCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCreateActionPerformed
    createRecord();
}//GEN-LAST:event_bCreateActionPerformed

private void cbShiftsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbShiftsActionPerformed
    checkShift();
}//GEN-LAST:event_cbShiftsActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCreate;
    private javax.swing.JComboBox cbShifts;
    private com.toedter.calendar.JDateChooser dcEndDate;
    private com.toedter.calendar.JDateChooser dcStartDate;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbCheckDate;
    private javax.swing.JLabel lbCheckShift;
    private javax.swing.JLabel lbChoise;
    private javax.swing.JLabel lbClose;
    private javax.swing.JLabel lbDep;
    private javax.swing.JLabel lbID;
    private javax.swing.JLabel lbMessage;
    // End of variables declaration//GEN-END:variables
}
